package com.sl.au.controller;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Account;
import com.sl.au.entity.BusinesssellerBaseInfo;
import com.sl.au.entity.BussinessLevel;
import com.sl.au.entity.User;
import com.sl.au.service.BusinesssellerBaseInfoService;
import com.sl.au.service.BussessllerbaseinfoExcelloadService;
import com.sl.au.service.BussinessLevelService;
import com.sl.au.service.RoleService;
import com.sl.au.service.UserService;
/*
 * 批量导入Excel
 */
import com.sl.utils.MsgHelper;
import com.sl.utils.SHA256Util;

@RestController
@RequestMapping(value = "/ui/bussinessbaseinfoExcelBulkload")
public class BussessllerbaseinfoExcelloadController extends BaseController {

	@Autowired
	BussessllerbaseinfoExcelloadService bussessllerbaseinfoExcelloadService;
	@Autowired
	private BusinesssellerBaseInfoService businesssellerBaseInfoService;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private BussinessLevelService bussinessLevelService;

	@RequestMapping(value = "/saveBussinessInfo", method = RequestMethod.POST)
	public MsgHelper saveBussinessInfo(@RequestParam(value = "file", required = false) MultipartFile file) {
		if (isRightFile(file)) {
			// 将文件上传到指定的磁盘中
			String excelPath = this.getUploadFilePath(this.fileUploadPath, "excel/bussinessBatch", file);
			// 从磁盘中读取文件信息并上传到数据库中
			excelPath = this.fileUploadPath + excelPath;

			try {
				Workbook workbook = null;
				String fileName = file.getOriginalFilename();
				if (fileName.endsWith(".xls")) {// 处理低版本
					workbook = new HSSFWorkbook(new FileInputStream(new File(excelPath)));
				}
				if (fileName.endsWith(".xlsx")) {// 处理高版本
					workbook = new XSSFWorkbook(new FileInputStream(new File(excelPath)));
				}
				Sheet sheet = workbook.getSheetAt(0);
				// List<BusinesssellerBaseInfo> list = new ArrayList<>();
				// List<User> users = new ArrayList<>();
				int lastRowNum = sheet.getLastRowNum();
				for (int i = 1; i <= lastRowNum; i++) {// 遍历每一行

					Row row = sheet.getRow(i);
					String name = row.getCell(0).getStringCellValue();
					if (name == null || "".equals(name)) {
						continue;
					}

					// 账号名称即商户名称
					Account account = null;

					User u = userService.getRepository().findByName(name);
					// 商户名称即用户名称
					User user = null;

					BusinesssellerBaseInfo b = null;
					if (u == null) {
						user = new User();
						account = new Account();
						b = new BusinesssellerBaseInfo();
					} else {
						b = businesssellerBaseInfoService.findByShopName(name);
						account = accountService.findByAccountName(name);
						user = userService.getRepository().findByName(name);
					}

					b.setShopName(name);
					b.setShopAdress(row.getCell(1).getStringCellValue());
					b.setManagementRange(row.getCell(2).getStringCellValue());
					if (row.getCell(3) == null || "".equals(row.getCell(3))) {
						b.setLongitude(0);
					} else {
						b.setLongitude(row.getCell(3).getNumericCellValue());
					}

					if (row.getCell(4) == null || "".equals(row.getCell(4))) {
						b.setLatitude(0);
					} else {
						b.setLatitude(row.getCell(4).getNumericCellValue());
					}

					if (row.getCell(5) == null || "".equals(row.getCell(5))) {
						b.setAreaMeasure(0);
					} else {
						// b.setAreaMeasure(row.getCell(5).getNumericCellValue());
						String am = row.getCell(5).getStringCellValue();
						String[] strs = am.split("=");
						String areaMeasure = "";
						if (strs.length > 1) {
							areaMeasure = strs[1];
						} else {
							areaMeasure = "0";
						}

						b.setAreaMeasure(Double.parseDouble(areaMeasure));
					}

					b.setSignPerson(row.getCell(6).getStringCellValue());// 签订人
					// 签订人电话
					DecimalFormat df = new DecimalFormat("0");
					double sp = row.getCell(7).getNumericCellValue();

					b.setSignPersonPhone(df.format(sp) + "");
					// 保洁员
					b.setCleaningPerson(row.getCell(8).getStringCellValue());
					// 保洁员电话
					double cp = row.getCell(9).getNumericCellValue();
					b.setCleaningPersonPhone(df.format(cp) + "");
					b.setMemo(row.getCell(10).getStringCellValue());
					String levelName = row.getCell(11).getStringCellValue();
					BussinessLevel bb = bussinessLevelService.findByLevelName(levelName);
					b.setBussinessLevel(bb);
					// list.add(b);
					user.setName(b.getShopName());
					account.setAccountName(b.getShopName());
					// 默认的密码

					account.setPassword(SHA256Util.getSHA256StrJava("123"));
					account.setMemo("123");
					account.setRole(roleService.findByName("商户"));

					// users.add(user);
					businesssellerBaseInfoService.saveMany(user, b, account);

				}
				// businesssellerBaseInfoService.getRepository().save(list);

			} catch (Exception e) {
				e.printStackTrace();

			}

		}
		return MsgHelper.success();

	}

	@RequestMapping(value = "/saveBussinessInfoWithPicture", method = RequestMethod.POST)
	public MsgHelper saveBussinessInfoWithPicture(
			@RequestParam(value = "filepic", required = false) MultipartFile[] file) {
		for (int i = 0; i < file.length; i++) {
			if (isRightImgFile(file[i])) {
				if (file[i].getOriginalFilename() != null && !"".equals(file[i].getOriginalFilename())) {
					// 注意路径的构建
					String name = file[i].getOriginalFilename();
					if (name.contains("/")) {
						String[] sp = name.split("/");
						name = sp[sp.length - 1];
					}
					if (name.contains(".")) {
						name = name.substring(0, name.lastIndexOf("."));
					}

					String url = getUploadFilePath(this.fileUploadPath, "img/Businessseller", file[i]);
					this.businesssellerBaseInfoService.savepicture(url, name);
				}
			} else {
				continue;
			}
		}
		return MsgHelper.success();
	}

	private boolean isRightImgFile(MultipartFile file) {
		String fileName = file.getOriginalFilename();
		return fileName != null && !"".equals(fileName) && (fileName.endsWith(".jpg") || fileName.endsWith(".gif")
				|| fileName.endsWith(".ico") || fileName.endsWith(".png"));
	}

	private boolean isRightFile(MultipartFile file) {
		String fileName = file.getOriginalFilename();
		return fileName != null && !"".equals(fileName) && (fileName.endsWith(".xlsx") || fileName.endsWith(".xls"));
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {

		ModelAndView modelAndView = this.createLayoutView("importExcel/import");

		return modelAndView;
	}

}
